package com.pyb.java.network.observers;


import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.exception.RxExceptionUtil;

import java.net.UnknownHostException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 数据返回统一处理  参考https://www.jianshu.com/p/ff619fea7e22
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<ResponseEntity<T>> {
    private static final String TAG = "BaseObserver";
    public Disposable disposable;

    @Override
    public void onNext(ResponseEntity<T> response) {
        //在这边对 基础数据 进行统一处理  举个例子：
        if (response.getStatus() == 200) {
            onSuccess(response.getData());
        } else {
            onFailure(null, response.getMsg(), false);
        }
    }

    @Override
    public void onError(Throwable e) {//服务器错误信息处理
        if (!disposable.isDisposed()) {
            disposable.dispose();
        }
        onFailure(e, RxExceptionUtil.exceptionHandler(e), RxExceptionUtil.isConnect(e));
    }

    @Override
    public void onComplete() {
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
    }

    @Override
    public void onSubscribe(Disposable d) {
        onFailure(new UnknownHostException(), RxExceptionUtil.exceptionHandler(new UnknownHostException()),true);
    }

    public abstract void onSuccess(T result);

    public abstract void onFailure(Throwable e, String errorMsg, boolean isNoConnected);

}
